import { createRouter, createWebHistory, type RouteRecordRaw, type Router } from 'vue-router'

//静态路由
const routes: Array<RouteRecordRaw> = [{
    path: '/',
    name: 'index',
    component: () => import('@/views/index.vue')
}, {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about.vue')
}, {
    //404
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
}, {
    //匹配404，从定向到404页面
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    redirect: '/404'
}]

const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior: (_to, _from, savedPosition) => {
        if (savedPosition) {
            return savedPosition
        }
    }
})

// 防止无限循环
let isAddingRoute = false
router.beforeEach(async (to, from, next) => {
    if (to.matched.length === 0 && !isAddingRoute) {
        // 如果没有匹配到路由，并且不在添加路由的过程中
        isAddingRoute = true
        // 加载动态路由
        // await addDynamicRoute(to.path)
        isAddingRoute = false
        // 重新尝试导航
        next({ ...to, replace: true })
    } else if (to.matched.length === 0) {
        // 如果还是没有匹配到路由，重定向到 404
        next({ name: '404', replace: true })
    } else {
        // 正常情况，继续导航
        next()
    }
})

// 初始化路由
function initRouter(): Router {
    return router
}
export { initRouter }